'use client';

import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { message } from 'antd';
import { SafeUser } from '@/types/auth';

interface AuthContextType {
  user: SafeUser | null;
  loading: boolean;
  login: (token: string, userInfo: SafeUser) => void;
  logout: () => void;
  updateUser: (userInfo: SafeUser) => void;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

interface AuthProviderProps {
  children: ReactNode;
}

export function AuthProvider({ children }: AuthProviderProps) {
  const [user, setUser] = useState<SafeUser | null>(null);
  const [loading, setLoading] = useState(true);
  const [justLoggedIn, setJustLoggedIn] = useState(false);
  const router = useRouter();
  const pathname = usePathname();
  const whiteList = ['/admin/login', '/admin/xlsx-process'];
  // 检查认证状态
  const checkAuth = async () => {
    // 如果刚刚登录，跳过 API 验证
    if (justLoggedIn) {
      setLoading(false);
      setJustLoggedIn(false);
      return;
    }

    try {
      const token = localStorage.getItem('token');
      const userInfo = localStorage.getItem('user_info');
      
      if (!token) {
        setLoading(false);
        return;
      }

      // 如果有本地存储的用户信息，先设置它
      if (userInfo) {
        try {
          const parsedUser = JSON.parse(userInfo);
          setUser(parsedUser);
        } catch (e) {
          console.error('解析本地用户信息失败:', e);
        }
      }


    } catch (error) {
      console.error('认证检查失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    checkAuth();
  }, []);

  // 路由守卫
  useEffect(() => {
    if (!loading) {
      const isLoginPage = pathname === '/admin/login';
      const isAuthenticated = !!user;
      const isWhiteList = whiteList.includes(pathname||'');
      if (!isAuthenticated && !isLoginPage && !isWhiteList) {
        // 未登录且不在登录页，跳转到登录页
        router.push('/admin/login');
      } else if (isAuthenticated && isLoginPage) {
        // 已登录且在登录页，跳转到首页
        router.push('/admin'); 
      }
    }
  }, [user, loading, pathname, router]);

  // 登录
  const login = (token: string, userInfo: SafeUser) => {
    localStorage.setItem('token', token);
    localStorage.setItem('user_info', JSON.stringify(userInfo));
    setUser(userInfo);
    setJustLoggedIn(true); // 标记刚刚登录
  };

  // 登出
  const logout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user_info');
    setUser(null);
    message.success('已安全退出');
    router.push('/admin/login');
  };

  // 更新用户信息
  const updateUser = (userInfo: SafeUser) => {
    setUser(userInfo);
    localStorage.setItem('user_info', JSON.stringify(userInfo));
  };

  const value: AuthContextType = {
    user,
    loading,
    login,
    logout,
    updateUser,
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
}

// 使用认证上下文的Hook
export function useAuth() {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
}